package com.vma.jifu.backsys.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.jifu.bizModel.model.Offer;
import com.vma.jifu.bizModel.model.OfferType;
import com.vma.jifu.offer.service.OfferService;
import com.vma.jifu.offer.service.impl.OfferServiceImpl;
import com.vma.tools.ReturnsUtil;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.http.client.HttpClient;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by kitabi on 2017/6/16.
 */
public class OfferController extends BaseController {

    OfferService offerService = new OfferServiceImpl();

    public void qryOfferList(){
        try {
            Integer cPage = getParaToInt("cPage");
            Integer pSize = getParaToInt("pSize");
            Integer typeId= getParaToInt("classify");
            String name =getPara("offerName");
            String mystatus = getPara("status");

            Page<Record> offer= offerService.qryOfferList(cPage,pSize,typeId,name,mystatus);
            renderJson(ReturnForm(offer.getList(),offer.getTotalRow()));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }
    }
    public void updateStatus(){
        try {

            String idlist =getPara("id");
            int mystatus = getParaToInt("status");
            String versionlist= getPara("version");

            String[] ids = idlist.split(",");
            String[] versions= versionlist.split(",");
            for(int i=0;i<ids.length;i++){
                String id= ids[i];
                String version= versions[i];
                Offer offer = Offer.dao.findById(id,version);
                offer.setStatus(mystatus).update();

            }

            renderJson(ReturnsUtil.returnSuccess("更新成功"));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }
    }

    public void getOfferDetail(){
        String id = getPara("id");
        String version= getPara("version");

        Offer offer = new Offer();
        if(id != null || version != null){
            offer = Offer.dao.findById(id,version);
            int offerpriec= offer.getOfferPrice();
            float offerprice = offerpriec/100;

            setAttr("d_offer_price",offerprice);
        }



        setAttr("initData",offer);

         List<OfferType> offerType = OfferType.dao.find("select * from offer_type ");

        setAttr("offerType",offerType);

        renderVelocity("/newshop/offer/goods/addgoods.html");
    }

    public void addOffer(){
        String offer_name= getPara("offer_name");
        String offer_price= getPara("offer_price");
        String idstring = getPara("id");
        int id=0;
        if(idstring != null && !"".equals(idstring)){
            id= Integer.valueOf(idstring);
        }

        int offer_type= getParaToInt("offer_type");
        String img_url= getPara("img_url");
        String video_url= getPara("video_url");
        String offer_detail = getPara("offer_detail");
        int is_hot = getParaToInt("is_hot");


        int version = 1;
        Offer offerold;
        if(id !=0){
            offerold= Offer.dao.findFirst("select * from offer where status in (0,1) and id="+id);
            if(offerold != null){
                version = offerold.getVersion()+1;
                offerold.setStatus(2).update();//更新旧的数据，改成状态2
            }
        }
        double temprice= Double.valueOf(offer_price)*100;
        int price = (int) temprice;//以分为单位

        Offer offer = new Offer();
        if(id !=0) {
            offer.setId(id);
            offer.setVersion(version+1);
        }else{
            offer.setVersion(1);
        }
        offer.setOfferName(offer_name);
        offer.setOfferPrice(price);
        offer.setOfferType(offer_type);
        offer.setImgUrl(img_url);
        offer.setVedioUrl(video_url);
        offer.setOfferDetail(offer_detail);
        offer.setCreateTime(new Date());
        offer.setIsHot(is_hot);
        offer.save();

        renderJson(ReturnsUtil.returnSuccess("操作成功"));
    }

    public void sendSms() throws Exception{

//        String video_url= getPara("name");
//        connectSmsAPI("13705949140",video_url);

            Integer x_ac=10;//发送信息
            HttpURLConnection httpconn = null;
            String result="Error";
            StringBuilder sb = new StringBuilder();
            sb.append("http://service.winic.org:8009/sys_port/gateway/index.asp?");

    //以下是参数
    //为了你的测试方便收到短信！请短信内容编辑为：你的验证码为：123456【中正云通信】
            sb.append("id=").append(URLEncoder.encode("13705949140", "gb2312"));
            sb.append("&pwd=").append("woai123");
            sb.append("&to=").append("13705949140");
            sb.append("&content=").append(URLEncoder.encode("发送测试内容", "gb2312"));
            sb.append("&time=").append("");
            try {
                URL url = new URL(sb.toString());
                httpconn = (HttpURLConnection) url.openConnection();
                BufferedReader rd = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
                result = rd.readLine();
                rd.close();
            } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
    // TODO Auto-generated catch block
                e.printStackTrace();
            } finally{
                if(httpconn!=null){
                    httpconn.disconnect();
                    httpconn=null;
                }

            }


        renderJson(ReturnsUtil.returnSuccess("设定成功"));
    }



}
